﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Middle.Request.Commission;
using BenCaoXuan.Infrastructure.Dto.Middle.Request.Customs;
using BenCaoXuan.Infrastructure.Dto.Middle.Request.Register;
using BenCaoXuan.Infrastructure.Dto.Middle.Response.customs;
using BenCaoXuan.Infrastructure.Dto.Middle.Response.Customs;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Redis;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.middle;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.middle
{
    [Inject_]
    public class Promote_Service : Base_Service, I_Promote_Service
    {
        private readonly Product_IOC _product_IOC;
        private readonly Customer_IOC _customer_IOC;
        private readonly Order_IOC _order_IOC;
        private readonly RedisStringService _redisStringService;
        private readonly IConfiguration _configuration;

        public Promote_Service(Customer_IOC customer_IOC,
            RedisStringService redisStringService,
           IConfiguration configuration,Order_IOC order_IOC,Product_IOC product_IOC)
        {
            _product_IOC = product_IOC;
            _customer_IOC = customer_IOC;
            _order_IOC = order_IOC;
            _redisStringService = redisStringService;
            _configuration = configuration;
        }
        /// <summary>
        /// 客户注册
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Register(Customs_Request_Dto dto)
        {
            var existsCustoms = _customer_IOC._customer_EFCore
                .GetAll(u => u.CPhone == dto.phone)
                .SingleOrDefault();

            if (existsCustoms != null)
            {
                return Get_Result(-1, "该手机号已注册，请直接登录");
            }

            var defaultPwd = "123456"; 
            var salt = Config.GUID2(); 
            var encryptedPwd = EncryptUtil.LoginMd5(defaultPwd, salt); 

            Custom custom = new Custom
            {
                CId = Config.GenerateCustomerNo(),
                CName = dto.name,
                CPhone = dto.phone,
                CPassword = encryptedPwd,
                CSalt = salt, 
                CCreateTime = DateTime.Now,
                CUpdateTime = DateTime.Now,
                CStatus = 2, // 2-待跟进
                CIsConvert =-1, // -1公海客户
                CResource = "04091b0602ea0002399423ced088b04f",
                CRemark = null
            };

            _customer_IOC._customer_EFCore.Add(custom);
            await _customer_IOC._customer_EFCore.SaveChangesAsync();

            var redisKey = _configuration["Redis:Keys:Middle_Check_Login"];
            if (!string.IsNullOrEmpty(redisKey))
            {
                var customerDto = new Customs_Dto
                {
                    id = custom.CId,
                    account = custom.CPhone,
                    name = custom.CName,
                    isConvert = custom.CIsConvert
                };
                _redisStringService.Set(
                    key: $"{redisKey}_{custom.CPhone}", 
                    value: JsonConvert.SerializeObject(customerDto)
                );
            }

            var resultData = new
            {
                id = custom.CId,
                name = custom.CName,
                phone = custom.CPhone,
                registerTime = custom.CCreateTime,
                defaultPassword = "123456"
            };



            return Get_Result(0, "注册成功", resultData);
        }

        #region 1. 登录后检查被推广人订单并处理佣金的接口（无事务版）
        /// <summary>
        /// 检查推广人的所有被推广人订单，仅≤5条且有有效订单时处理佣金（含积分）
        /// </summary>
        /// <param name="customerId">推广人ID（当前登录客户ID）</param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Check_InviteeCommission(string customerId)
        {
            // 1. 基础参数验证
            if (string.IsNullOrEmpty(customerId))
            {
                return Get_Result(-1, "推广人ID不能为空");
            }

            try
            {
                // 2. 查询推广人的所有被推广人（去重）
                var inviteeList = await _customer_IOC._customerVipCpsCommission_EFCore.GetAll()
                    .Where(c => c.CcvcPromoterId == customerId)
                    .Select(c => c.CcvcInviteeId)
                    .Distinct()
                    .ToListAsync();

                if (!inviteeList.Any())
                {
                    return Get_Result(0, "当前推广人暂无被推广人，无需处理佣金");
                }

                var processedResult = new List<string>();
                bool isPointsAdded = false;

                // 3. 遍历每个被推广人单独处理
                foreach (var inviteeId in inviteeList)
                {
                    try
                    {
                        // 3.1 获取当前被推广人的前5条已支付订单（按时间倒序）
                        var inviteeOrders = await _order_IOC._orders_EFCore.GetAll()
                            .Where(o => o.OCustomerId == inviteeId && o.OPayStatus == 1)
                            .OrderByDescending(o => o.OCreateTime)
                            .Take(5) // 严格限制每个被推广人只取前5条订单
                            .ToListAsync();

                        if (!inviteeOrders.Any())
                        {
                            processedResult.Add($"被推广人[{inviteeId}]：无有效订单，跳过处理");
                            continue;
                        }

                        // 3.2 查询当前被推广人的推广链接
                        var promotionLink = await _customer_IOC._customerVipCpsCommission_EFCore.GetAll()
                            .Where(c => c.CcvcPromoterId == customerId && c.CcvcInviteeId == inviteeId)
                            .Select(c => c.CcvcCps)
                            .FirstOrDefaultAsync() ?? string.Empty;

                        // 3.3 处理当前被推广人的每个订单
                        foreach (var order in inviteeOrders)
                        {
                            // 检查订单是否已处理过佣金
                            bool isOrderProcessed = await _customer_IOC._customerVipCpsCommission_EFCore.GetAll()
                                .AnyAsync(c => c.CcvcTriggerNo == order.OId);

                            if (isOrderProcessed)
                            {
                                processedResult.Add($"被推广人[{inviteeId}]：订单[{order.OId}]已处理过佣金，跳过");
                                continue;
                            }

                            // 计算该订单的佣金金额
                            decimal commissionAmount = await CalculateBaseAmountByProduct(inviteeId, order.OId); // 传入订单ID更精准

                            // 构造佣金数据
                            var commissionDto = new Commission_Request_Dto
                            {
                                promoterId = customerId,
                                inviteeId = inviteeId,
                                triggerType = 2, // 被推广人消费类型
                                cps = promotionLink,
                                commissionAmount = commissionAmount,
                                orderId = order.OId,
                                orderTime = order.OCreateTime
                            };

                            // 创建佣金记录
                            await CreateOrUpdateCommission(commissionDto);
                            processedResult.Add($"被推广人[{inviteeId}]：订单[{order.OId}]佣金处理成功，金额：{commissionAmount}");
                        }

                        // 3.4 为推广人添加积分（仅添加一次）
                        if (!isPointsAdded)
                        {
                            isPointsAdded = await AddPromoterPoints(customerId);
                        }
                    }
                    catch (Exception ex)
                    {
                        processedResult.Add($"被推广人[{inviteeId}]：处理失败，原因：{ex.Message}");
                    }
                }

                // 4. 处理积分结果提示
                if (!isPointsAdded && inviteeList.Any())
                {
                    processedResult.Add($"推广人[{customerId}]：积分添加失败（可能无VIP记录）");
                }

                // 5. 返回处理结果
                return Get_Result(0, "被推广人前5条未处理订单佣金处理完成", new
                {
                    totalInvitee = inviteeList.Count,
                    processedOrderCount = processedResult.Count(r => r.Contains("处理成功")),
                    failedCount = processedResult.Count(r => r.Contains("处理失败")),
                    processedDetails = processedResult,
                    isPointsAdded = isPointsAdded
                });
            }
            catch (Exception ex)
            {
                return Get_Result(-1, $"佣金处理失败：{ex.Message}");
            }
        }


        #endregion

        /// <summary>
        /// 查询被推广人的订单数量（所有状态，用于判断是否≤5）
        /// </summary>
        private async Task<int> GetInviteeOrderCount(string inviteeId)
        {
            var count = await _order_IOC._orders_EFCore.GetAll()
                .CountAsync(o => o.OCustomerId == inviteeId);
            return count;
        }

        /// <summary>
        /// 创建佣金记录（触发类型2：被推广人消费，仅订单数≤5且有有效订单时生成有效佣金）
        /// </summary>
        private async Task<CustomerVipCcpsCommission> CreateOrUpdateCommission(Commission_Request_Dto dto)
        {
            // 1. 修正触发类型（仅支持1或2）
            if (dto.triggerType != 1 && dto.triggerType != 2)
            {
                dto.triggerType = 1;
            }

            // 2. 核心参数校验
            if (string.IsNullOrEmpty(dto.promoterId) || string.IsNullOrEmpty(dto.inviteeId))
            {
                throw new ArgumentException("推广人ID和被推广人ID不能为空", nameof(dto));
            }

            // 3. 订单数判断（≤5才计算有效佣金）
            int inviteeTotalOrderCount = await GetInviteeOrderCount(dto.inviteeId!);
            bool isOrderCountValid = inviteeTotalOrderCount <= 5;

            // 4. 有效订单校验（仅OPayStatus=1的订单参与计算）
            var validOrder = await _order_IOC._orders_EFCore.GetAll()
                .FirstOrDefaultAsync(o => o.OCustomerId == dto.inviteeId && o.OPayStatus == 1);
            bool hasValidOrder = validOrder != null;

            // 5. 佣金金额计算（仅订单数≤5且有有效订单时）
            decimal commissionAmount = 0;
            if (isOrderCountValid && hasValidOrder && validOrder != null) // 新增validOrder非空判断
            {
                commissionAmount = await CalculateBaseAmountByProduct(dto.inviteeId!, validOrder.OId); // 传递orderId参数
            }

            // 6. 去重校验（同一订单仅生成一次佣金）
            if (validOrder != null && !string.IsNullOrEmpty(validOrder.OId))
            {
                bool isOrderProcessed = await _customer_IOC._customerVipCpsCommission_EFCore.GetAll()
                    .AnyAsync(c => c.CcvcTriggerNo == validOrder.OId);
                if (isOrderProcessed)
                {
                    throw new Exception($"订单[{validOrder.OId}]已生成过佣金，请勿重复提交");
                }
                Console.WriteLine($"订单[{validOrder.OId}]未处理过佣金，可生成新记录");
            }

            // 7. 创建佣金记录（区分有效/无效佣金场景）
            var newCommission = new CustomerVipCcpsCommission
            {
                CcvcId = Config.GenerateTId(),
                CcvcPromoterId = dto.promoterId!,
                CcvcInviteeId = dto.inviteeId!,
                CcvcCps = dto.cps ?? string.Empty,
                CcvcTriggerType = (sbyte)dto.triggerType.Value,
                CcvcTriggerNo = validOrder?.OId ?? string.Empty,
                CcvcCommissionAmount = commissionAmount,
                CcvcCommissionRate = 0.05m,
                CcvcBaseAmount = commissionAmount,
                CcvcCommissionStatus = 1,
                CcvcCreateTime = DateTime.Now,
                CcvcUpdateTime = DateTime.Now,
                CcvcRemark = isOrderCountValid && hasValidOrder
                    ? "正常计算佣金"
                    : $"订单数{inviteeTotalOrderCount}＞5 或 无有效订单，无佣金"
            };

            // 8. 保存到数据库
            _customer_IOC._customerVipCpsCommission_EFCore.Add(newCommission);
            await _customer_IOC._customerVipCpsCommission_EFCore.SaveChangesAsync();
            return newCommission;
        }
        /// <summary>
        /// 计算触发类型为2时的基数金额（产品/套餐佣金比例 * 规格/套餐售价）
        /// </summary>
        private async Task<decimal> CalculateBaseAmountByProduct(string inviteeId, string orderId)
        {
            decimal totalCommission = 0;

            // 1. 验证订单有效性（必须属于当前被推广人且已支付）
            var validOrder = await _order_IOC._orders_EFCore.GetAll()
                .FirstOrDefaultAsync(o =>
                    o.OId == orderId &&  // 精确匹配当前订单ID
                    o.OCustomerId == inviteeId &&
                    o.OPayStatus == 1);

            if (validOrder == null)
            {
                Console.WriteLine($"订单[{orderId}]无效或不属于被推广人[{inviteeId}]");
                return totalCommission;
            }

            // 2. 获取该订单的所有详情（可能包含多个产品/套餐）
            var orderDetails = await _order_IOC._ordersDetails_EFCore.GetAll()
                .Where(od => od.OdOrderId == orderId)
                .ToListAsync();  // 使用ToList获取所有详情，支持多商品订单

            if (!orderDetails.Any())
            {
                Console.WriteLine($"订单[{orderId}]无详情记录");
                return totalCommission;
            }

            // 3. 遍历所有订单详情计算佣金
            foreach (var detail in orderDetails)
            {
                // 3.1 处理产品规格佣金
                if (!string.IsNullOrEmpty(detail.OdProductId))
                {
                    string[] productIds = detail.OdProductId.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var productID in productIds)
                    {
                        
                        // 获取产品规格信息
                        var productSpec = await _product_IOC._productSpecs_EFCore.GetAll()
                            .FirstOrDefaultAsync(ps => ps.PsId == productID);

                        if (productSpec == null)
                        {
                            Console.WriteLine($"产品规格[{productID}]不存在");
                            continue;
                        }

                        // 获取对应产品ID
                        var productId = productSpec.PsProductId;
                        if (string.IsNullOrEmpty(productId))
                        {
                            Console.WriteLine($"产品规格[{productId}]未关联产品");
                            continue;
                        }

                        // 获取佣金规则
                        var commissionRule = await _customer_IOC._commissionRules_EFCore.GetAll()
                            .FirstOrDefaultAsync(cr => cr.CrProductId == productId);

                        if (commissionRule == null)
                        {
                            Console.WriteLine($"产品[{productId}]未设置佣金规则");
                            continue;
                        }

                        // 计算产品佣金（确保价格有效）
                        if (productSpec.PsPrice.HasValue && productSpec.PsPrice > 0)
                        {
                            decimal productCommission = (commissionRule.CrCommissionRate / 100m) * (decimal)productSpec.PsPrice.Value;
                            totalCommission += productCommission;
                            Console.WriteLine($"订单[{orderId}]产品[{productId}]佣金：{productCommission}");
                        }
                    }
                }

                // 3.2 处理套餐佣金
                if (!string.IsNullOrEmpty(detail.OdPackageId))
                {
                    string[] packageIds = detail.OdPackageId.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var packageId in packageIds)
                    {
                        // 获取套餐信息
                        var package = await _product_IOC._productPackage_EFCore.GetAll()
                            .FirstOrDefaultAsync(p => p.PpId == packageId);

                        if (package == null)
                        {
                            Console.WriteLine($"套餐[{packageId}]不存在");
                            continue;
                        }

                        // 获取套餐佣金规则
                        var packageRule = await _customer_IOC._commissionRules_EFCore.GetAll()
                            .FirstOrDefaultAsync(cr => cr.CrPackageId == packageId);

                        if (packageRule == null)
                        {
                            Console.WriteLine($"套餐[{packageId}]未设置佣金规则");
                            continue;
                        }

                        // 计算套餐佣金（确保价格有效）
                        if (package.PpPrice.HasValue && package.PpPrice > 0)
                        {
                            // 假设CrCommissionRate是百分比（如5表示5%）
                            decimal packageCommission = (packageRule.CrCommissionRate / 100m) * (decimal)package.PpPrice.Value;
                            totalCommission += packageCommission;
                            Console.WriteLine($"订单[{orderId}]套餐[{packageId}]佣金：{packageCommission}");
                        }
                    }
                }
            }

            Console.WriteLine($"订单[{orderId}]总佣金：{totalCommission}");
            return totalCommission;
        }


        /// <summary>
        /// 为推广人增加积分（一次接口调用仅加一次）
        /// </summary>
        private async Task<bool> AddPromoterPoints(string promoterId)
        {
            Console.WriteLine($"开始为推广人[{promoterId}]添加积分");
            var promoterVip = await _customer_IOC._customerVip_EFCore.GetAll()
                .FirstOrDefaultAsync(cv => cv.CvCustomerId == promoterId);

            if (promoterVip == null)
            {
                return false;
            }

            promoterVip.CvPoint += 5;
            _customer_IOC._customerVip_EFCore.Update(promoterVip);
            int affectedRows = await _customer_IOC._customerVip_EFCore.SaveChangesAsync();

            bool result = affectedRows > 0;
            return result;
        }

        /// <summary>
        /// 新增或累加佣金（对外接口，包含完整错误处理）
        /// </summary>
        public async Task<Api_Result_Dto> Add_CustomerCommission(Commission_Request_Dto dto)
        {
            Console.WriteLine($"DTO参数：promoterId={dto.promoterId}, inviteeId={dto.inviteeId}, triggerType={dto.triggerType}");
            try
            {

                var commission = await CreateOrUpdateCommission(dto);
                var isPointsAdded = await AddPromoterPoints(dto.promoterId!);

                if (!isPointsAdded)
                {
                    return Get_Result(-1, "佣金处理成功，但积分未更新", commission);
                }

                return Get_Result(0, "佣金处理成功，积分已增加", commission);
            }
            catch (ArgumentException ex)
            {
                return Get_Result(-1, ex.Message, null);
            }
            catch (Exception ex)
            {
                if (ex is DbUpdateException)
                {
                    return Get_Result(-1, "数据库更新失败，请稍后重试", null);
                }
                else if (ex.Message.Contains("已生成过佣金"))
                {
                    return Get_Result(-1, "该订单已处理过佣金，请勿重复提交", null);
                }
                return Get_Result(-1, "操作失败，请稍后重试", null);
            }
        }





        /// <summary>
        /// 新增VIP客户并更新客户表为正式客户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Add_VipCustomer(VipCustomer_Request_Dto dto)
        {
            try
            {
                // 1. 检查客户是否已存在（根据客户ID）
                var existingCustomer = await _customer_IOC._customer_EFCore
                    .GetAll(c => c.CId == dto.cId)
                    .FirstOrDefaultAsync();

                if (existingCustomer == null)
                {
                    return Get_Result(-1, "客户不存在，无法新增VIP客户", null);
                }

                // 2. 检查客户是否已为VIP（避免重复创建）
                var existingVip = await _customer_IOC._customerVip_EFCore
                    .GetAll(v => v.CvCustomerId == dto.cId)
                    .FirstOrDefaultAsync();

                if (existingVip != null)
                {
                    return Get_Result(0, "客户已是VIP，无需重复创建", existingVip);
                }

                CustomerVip customerVip = new CustomerVip
                {
                    CvId = Config.GenerateTId(),
                    CvCustomerId = dto.cId!,
                    CvCreateTime = DateTime.Now,
                    CvGetTime = DateTime.Now,
                    CvPoint = 0,
                    CvStatus = dto.status = 1,
                    CvVipcode = Config.GUID2(), // 确保唯一
                };

                _customer_IOC._customerVip_EFCore.Add(customerVip);
                await _customer_IOC._customerVip_EFCore.SaveChangesAsync();

                // 5. 更新客户表为正式客户
                existingCustomer.CIsConvert = 1;
                await _customer_IOC._customer_EFCore.SaveChangesAsync();

                return Get_Result(0, "新增VIP客户并更新客户状态成功，积分同步完成", customerVip);
            }
            catch (Exception ex)
            {
                return Get_Result(-1, "新增VIP客户失败，请稍后重试", null);
            }
        }
        /// <summary>
        /// 检查客户是否为VIP
        /// </summary>
        /// <param name="customerId">客户ID</param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> CheckIsVip(string customerId)
        {
            // 从VIP表中查询是否存在该客户的VIP记录
            var isVip = await _customer_IOC._customerVip_EFCore
                .GetAll(cv => cv.CvCustomerId == customerId)
                .AnyAsync();

            return Get_Result(0);
        }


        /// <summary>
        /// 根据注册人ID查询推广链接记录
        /// </summary>
        /// <param name="registerId">注册人ID</param>
        /// <returns>推广链接记录</returns>
        private async Task<CustomerVipCp> GetCpsRecordByRegisterId(string registerId)
        {
            if (string.IsNullOrEmpty(registerId))
            {
                return null;
            }

            return await _customer_IOC._customerVipCPS_EFCore
                .GetAll(cps => cps.CvcRegisterId! == registerId)
                .FirstOrDefaultAsync();
        }

        /// <summary>
        /// 根据用户ID查询VIP信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>VIP信息</returns>
        private async Task<CustomerVip> GetVipInfoByUserId(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return null;
            }

            return await _customer_IOC._customerVip_EFCore
                .GetAll(vip => vip.CvCustomerId == userId)
                .FirstOrDefaultAsync();
        }

        /// <summary>
        /// 给VIP用户累加积分
        /// </summary>
        /// <param name="vipInfo">VIP信息</param>
        /// <param name="points">要添加的积分</param>
        /// <returns>是否更新成功</returns>
        private async Task<bool> AddVipPoints(CustomerVip vipInfo, int points)
        {
            if (vipInfo == null || points <= 0)
            {
                return false;
            }

            var originalPoint = vipInfo.CvPoint;
            vipInfo.CvPoint += points;

            _customer_IOC._customerVip_EFCore.Update(vipInfo);
            var affectedRows = await _customer_IOC._customerVip_EFCore.SaveChangesAsync();

            if (affectedRows > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 更新推广链接的积分发放状态（0=未发放，1=已发放）
        /// </summary>
        /// <param name="cpsId">推广链接ID</param>
        /// <returns>是否更新成功</returns>
        private async Task<bool> UpdateCpsPointsGivenStatus(string cpsId)
        {
            if (string.IsNullOrEmpty(cpsId))
            {
                return false;
            }

            // 查询推广链接记录
            var cpsRecord = await _customer_IOC._customerVipCPS_EFCore
                .GetAll(cps => cps.CvcId == cpsId)
                .FirstOrDefaultAsync();

            if (cpsRecord == null)
            {
                return false;
            }

            // 标记为已发放（1）
            cpsRecord.CvcIsPointsGiven = 1;
            _customer_IOC._customerVipCPS_EFCore.Update(cpsRecord);
            var affectedRows = await _customer_IOC._customerVipCPS_EFCore.SaveChangesAsync();

            if (affectedRows > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 给推广人积分累加5分（同一推广关系仅首次消费时添加）
        /// </summary>
        /// <param name="registerId">注册人ID</param>
        /// <returns>操作结果</returns>
        public async Task<Api_Result_Dto> AddPromoterVipPoints(string registerId)
        {
            try
            {
                // 1. 查询推广链接记录
                var cpsRecord = await GetCpsRecordByRegisterId(registerId);
                if (cpsRecord == null)
                {
                    return Get_Result(-1, "未找到对应的推广记录", null);
                }

                // 2. 判断是否已发放过积分（1=已发放，不重复添加）
                if (cpsRecord.CvcIsPointsGiven == 1)
                {
                    return Get_Result(0, "同一推广关系仅能获得一次积分，无需重复操作", new
                    {
                        PromoterId = cpsRecord.CvcCustomerId,
                        RegisterId = registerId,
                        CvcIsPointsGiven = 1
                    });
                }

                // 3. 查询推广人VIP信息
                var promoterVip = await GetVipInfoByUserId(cpsRecord.CvcCustomerId!);
                if (promoterVip == null)
                {
                    return Get_Result(-1, "推广人不是VIP，无法添加积分", null);
                }

                // 4. 给推广人加5积分
                var isSuccess = await AddVipPoints(promoterVip, 5);
                if (!isSuccess)
                {
                    return Get_Result(-1, "推广人积分更新失败", null);
                }

                // 5. 更新积分发放状态为已发放（1）
                var isStatusUpdated = await UpdateCpsPointsGivenStatus(cpsRecord.CvcId);
                if (!isStatusUpdated)
                {
                    Console.WriteLine($"警告：推广人积分已添加，但状态更新失败，需人工标记CvcId={cpsRecord.CvcId}为1");
                    return Get_Result(0, "推广人积分已增加，但积分发放状态更新失败，请联系管理员", new
                    {
                        PromoterId = cpsRecord.CvcCustomerId,
                        NewPoints = promoterVip.CvPoint,
                        CvcIsPointsGiven = 0, // 状态未更新成功，仍为0
                        Warning = "积分发放状态未同步，需人工处理"
                    });
                }

                return Get_Result(0, "推广人积分成功增加5分", new
                {
                    PromoterId = cpsRecord.CvcCustomerId,
                    RegisterId = registerId,
                    NewPoints = promoterVip.CvPoint,
                    CvcIsPointsGiven = 1// 已成功更新为发放状态
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理积分时发生异常：{ex.ToString()}");
                return Get_Result(-1, "操作失败，请稍后重试", null);
            }
        }

        /// <summary>
        /// 获取佣金排名前五的客户
        /// </summary>
        /// <returns>包含客户佣金及VIP信息的列表</returns>
        public async Task<Api_Result_Dto> Get_Top_FiveCommission()
        {
            try
            {
                var topFiveCustomers = await _customer_IOC._customerVipCpsCommission_EFCore.GetAll()
     .GroupBy(c => c.CcvcPromoterId)
     .Select(g => new
     {
         CustomerId = g.Key,
         TotalCommission = g.Sum(c => c.CcvcCommissionAmount),
         CommissionRate = g.First().CcvcCommissionRate ?? 0m,
         OrderCount = g.Count()
     })
     .OrderByDescending(g => g.TotalCommission)
     .Take(5)
     .ToListAsync();

                if (!topFiveCustomers.Any())
                {
                    return Get_Result(0, "暂无佣金记录");
                }

                // 2. 提取所有客户ID
                var customerIds = topFiveCustomers.Select(g => g.CustomerId).ToList();

                // 3. 批量查询VIP信息（积分）
                var vipDict = await _customer_IOC._customerVip_EFCore.GetAll()
                    .Where(v => customerIds.Contains(v.CvCustomerId))
                    .ToDictionaryAsync(
                        keySelector: v => v.CvCustomerId,
                        elementSelector: v => new
                        {
                            Point = (int)(v.CvPoint ?? 0)
                        }
                    );

                // 4. 批量查询客户名称
                var customerDict = await _customer_IOC._customer_EFCore.GetAll()
                    .Where(c => customerIds.Contains(c.CId))
                    .ToDictionaryAsync(
                        keySelector: c => c.CId,
                        elementSelector: c => c.CName ?? "未知客户"
                    );

                // 5. 组装结果
                var result = topFiveCustomers.Select(g =>
                {
                    vipDict.TryGetValue(g.CustomerId, out var vipInfo);
                    customerDict.TryGetValue(g.CustomerId, out var customerName);

                    return new Commission_Request_Dto
                    {
                        CustomerName = customerName ?? "未知客户",
                        Point = vipInfo != null ? (decimal)vipInfo.Point : 0m,
                        OrderCount = g.OrderCount,
                        IncomeRate = $"{g.CommissionRate * 5:F2}%",
                        commissionAmount = g.TotalCommission
                    };
                }).ToList();

                return Get_Result(0, "查询成功", result);
            }
            catch (Exception ex)
            {
                return Get_Result(-1, $"查询失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 获取该客户的消费、积金、佣金
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Get_CustomerFinance(string customerId)
        {
            try
            {
                if (string.IsNullOrEmpty(customerId))
                {
                    return Get_Result(-1, "客户ID不能为空");
                }

                // 1. 查询积分（从Customer_Vip表）
                var vipInfo = await _customer_IOC._customerVip_EFCore.GetAll()
                    .Where(v => v.CvCustomerId == customerId)
                    .FirstOrDefaultAsync();
                decimal point = vipInfo?.CvPoint ?? 0m;

                // 2. 查询消费总金额（从Order表求和）
                decimal totalConsume = await _order_IOC._orders_EFCore.GetAll()
                    .Where(o => o.OCustomerId == customerId)
                    .SumAsync(o => (decimal?)o.OTotalAmount ?? 0m);

                // 3. 查询推广人佣金（从佣金表求和）
                decimal totalCommission = await _customer_IOC._customerVipCpsCommission_EFCore.GetAll()
                    .Where(c => c.CcvcPromoterId == customerId)
                    .SumAsync(c => (decimal?)c.CcvcCommissionAmount ?? 0m);

                // 4. 组装结果（可根据实际DTO调整）
                var result = new CustomerFinance_Response_Dto
                {
                    CustomerId = customerId,
                    Point = point,
                    TotalConsume = totalConsume,
                    TotalCommission = totalCommission
                };

                return Get_Result(0, "查询成功", result);
            }
            catch (Exception ex)
            {
                return Get_Result(-1, $"查询失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 获取消费
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public async Task<Api_Result_Dto> Get_CustomerConsumeStats(string customerId)
        {
            if (string.IsNullOrEmpty(customerId))
            {
                return Get_Result(-1, "客户ID不能为空");
            }

            try
            {
                // 1. 查询总消费（所有已支付订单的总金额）
                decimal? totalConsumeNullable = await _order_IOC._orders_EFCore.GetAll()
                    .Where(o => o.OCustomerId == customerId && o.OPayStatus == 1)
                    .SumAsync(o => (decimal?)o.OTotalAmount);
                decimal totalConsume = totalConsumeNullable ?? 0;

                // 2. 查询本月消费（当月已支付订单的总金额）
                DateTime monthStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                DateTime monthEnd = monthStart.AddMonths(1).AddDays(-1);
                decimal? monthlyConsumeNullable = await _order_IOC._orders_EFCore.GetAll()
                    .Where(o => o.OCustomerId == customerId && o.OPayStatus == 1
                        && o.OCreateTime >= monthStart && o.OCreateTime <= monthEnd)
                    .SumAsync(o => (decimal?)o.OTotalAmount);
                decimal monthlyConsume = monthlyConsumeNullable ?? 0;

                // 3. 查询今日消费（当天已支付订单的总金额）
                DateTime todayStart = DateTime.Today;
                DateTime todayEnd = todayStart.AddDays(1).AddSeconds(-1);
                decimal? dailyConsumeNullable = await _order_IOC._orders_EFCore.GetAll()
                    .Where(o => o.OCustomerId == customerId && o.OPayStatus == 1
                        && o.OCreateTime >= todayStart && o.OCreateTime <= todayEnd)
                    .SumAsync(o => (decimal?)o.OTotalAmount);
                decimal dailyConsume = dailyConsumeNullable ?? 0;

                var result = new CustomerFinance_Response_Dto
                {
                    TotalConsume = totalConsume,
                    MonthlyConsume = monthlyConsume,
                    DailyConsume = dailyConsume
                };

                return Get_Result(0, "查询成功", result);
            }
            catch (Exception ex)
            {
                return Get_Result(-1, $"查询消费数据失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 获取消费统计数据（按日、周、月分组）
        /// </summary>
        public async Task<Api_Result_Dto> Get_ConsumeStats(string customerId, string dateRange)
        {
            if (string.IsNullOrEmpty(customerId))
                throw new ArgumentException("用户ID不能为空");

            DateTime startTime = DateTime.MinValue;
            DateTime endTime = DateTime.MaxValue;
            var statsDto = new CustomerFinance_Response_Dto
            {
                CustomerId = customerId // 赋值用户ID
            };

            // 1. 根据时间范围初始化标签和时间边界
            switch (dateRange.ToLower())
            {
                case "week":
                    startTime = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + 1);
                    endTime = startTime.AddDays(6).AddSeconds(-1);
                    statsDto.TimeLabels = new List<string> { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
                    break;
                default:
                    throw new ArgumentException("无效时间范围：仅支持day/week/month");
            }

            // 2. 查询指定用户在时间范围内的已支付订单
            var validOrders = await _order_IOC._orders_EFCore.GetAll(
                 d => d.OCustomerId == customerId
                      && d.OPayStatus == 1  // 已支付状态
                      && d.OCreateTime >= startTime
                      && d.OCreateTime <= endTime
            ).Select(o => new { o.OCreateTime, o.OTotalAmount }).ToListAsync();

            // 3. 按时间段分组计算消费金额
            foreach (var label in statsDto.TimeLabels)
            {
                DateTime groupStart = startTime;
                DateTime groupEnd = endTime;

            if (dateRange == "week")
                {
                    var dayIndex = statsDto.TimeLabels.IndexOf(label);
                    groupStart = startTime.AddDays(dayIndex);
                    groupEnd = groupStart.AddDays(1).AddSeconds(-1);
                }

                // 累加当前分组的消费金额（处理空值）
                var groupConsume = validOrders
                    .Where(o => o.OCreateTime >= groupStart && o.OCreateTime <= groupEnd)
                    .Sum(o => o.OTotalAmount ?? 0);
                statsDto.ConsumeAmounts.Add(groupConsume);
            }

            // 4. 计算汇总信息（直接赋值到DTO的对应字段）
            // 总消费（所有已支付订单）
            statsDto.TotalConsume = await _order_IOC._orders_EFCore.GetAll(
                o => o.OCustomerId == customerId && o.OPayStatus == 1
            ).SumAsync(o => o.OTotalAmount ?? 0);

            // 本月消费
            var monthStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            statsDto.MonthlyConsume = await _order_IOC._orders_EFCore.GetAll(
                o => o.OCustomerId == customerId
                     && o.OPayStatus == 1
                     && o.OCreateTime >= monthStart
            ).SumAsync(o => o.OTotalAmount ?? 0);


            // 总订单数
            statsDto.TotalOrderCount = await _order_IOC._orders_EFCore.GetAll(
                o => o.OCustomerId == customerId && o.OPayStatus == 1
            ).CountAsync();

            return Get_Result(0,"ok",statsDto);
        }

        /// <summary>
        /// 给推广人添加推广成功的注册佣金数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> AddCustomerCommissionByRegister(AddCustomerCommissionByRegister_Dto dto)
        {
            CustomerVipCcpsCommission customerVipCcpsCommission = new CustomerVipCcpsCommission()
            {
                CcvcId = Config.GenerateTId(),
                CcvcBaseAmount = 0,
                CcvcCps = dto.cps,
                CcvcCommissionAmount = 5,
                CcvcCommissionStatus = 1,
                CcvcCreateTime = DateTime.Now,
                CcvcInviteeId = dto.inviteeId,
                CcvcOperatorId = null,
                CcvcPromoterId = dto.promoterId,
                CcvcReleaseTime = null,
                CcvcRemark = "推广成功获取的佣金",
                CcvcTriggerType = 1,
                CcvcUpdateTime = DateTime.Now
            };

            _customer_IOC._customerVipCpsCommission_EFCore.Add(customerVipCcpsCommission);
            var result = await _customer_IOC._customerVipCpsCommission_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }
    
    }
}
